import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-dialog-pics',
  templateUrl: './dialog-pics.component.html',
  styleUrls: ['./dialog-pics.component.scss']
})
export class DialogPicsComponent implements OnInit {
  @Input() type: string;
  @Input() pics: any[];

  picVisible: boolean = false;
  nzFooter: any = null;
  picItem: any = {};
  isDownload: boolean = false;

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
  }

  onPreview(item) {
    console.log(this.type);
    this.picItem = item;
    this.picVisible = true;
  }

  onDownload(item) {
    if (this.type == 'pic') {
      this.downloadImg(item.wjcflj, item.wjm);
    } else {
      this.download(item.wjcflj, item.wjm);
    }
  }

  downloadImg(url, name): void {
    this.isDownload = true;
    const image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext('2d');
      context.drawImage(image, 0, 0, image.width, image.height);
      const dataUrl = canvas.toDataURL('image/png');
      const a = document.createElement('a');
      const event = document.createEvent('MouseEvents');
      event.initMouseEvent(
        'click',
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null,
      );
      a.download = name;
      a.href = dataUrl;
      a.dispatchEvent(event);
      this.isDownload = false;
    };
    image.src = url;
  }

  download(fileUrl, name): void {
    // const reader = new FileReader();
    // reader.readAsDataURL(fileUrl)
    // reader.onload = (evt) => {
    //   debugger
    //   console.log(evt.target.result);
    // };
  }
}
